package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"teacher-helper/global"
	"teacher-helper/models"
	"teacher-helper/models/request"
	"teacher-helper/service"
)

func GetAllMenuTree(c *gin.Context) {
	request_type := c.Query("type")
	menus, sort_list, err := service.GetAllMenuTree(request_type)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取菜单列表成功", "data": map[string]interface{}{
			"menus": menus,
			"sort_list": sort_list,
		}})
	}
	return
}

func GetRoleMenuTree(c *gin.Context) {
	claims, _ := c.Get("claims")
	user := claims.(*request.CustomClaims)
	menus, menu_path_map, err := service.GetRoleMenuTree(user.RoleId)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取菜单列表成功",
			"data": map[string]interface{}{
				"menus":         menus,
				"menu_path_map": menu_path_map,
			},
		})
	}
	return
}

func GetMenuList(c *gin.Context) {
	var queryInfo request.QueryInfo
	if err := c.ShouldBind(&queryInfo); err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	menus, total, err := service.GetMenuList(queryInfo)
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取菜单列表成功", "data": map[string]interface{}{
			"menus": menus,
			"total": total,
		}})
	}
	return
}

func AddMenu(c *gin.Context) {
	var menu models.SysBaseMenu
	err := c.ShouldBindJSON(&menu)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	err = service.AddMenu(menu)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "添加菜单成功", "data": nil})
	}
	return
}

func GetParentIds(c *gin.Context) {
	parent_id, ok := c.GetQuery("parent_id")
	parentId, err := strconv.Atoi(parent_id)
	if !ok || err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	parent_id_list, err := service.GetMenuParentIds(uint(parentId))
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "查询菜单父ID成功", "data": parent_id_list})
	}
	return
}

func UpdateMenu(c *gin.Context) {
	var menu models.SysBaseMenu
	if err := c.ShouldBindJSON(&menu); err != nil {
		global.Logger.Error(err.Error())
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.UpdateMenuInfo(menu)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "修改菜单成功", "data": nil})
	}
	return
}

func DeleteMenu(c *gin.Context) {
	menu_id, ok := c.GetQuery("id")
	menuId, err := strconv.Atoi(menu_id)
	if !ok || err != nil {
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err = service.DeleteMenu(uint(menuId))
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "删除菜单成功", "data": nil})
	}
	return
}
